//
//  STHeartViewController.swift
//  BasicAnimation-Swift
//
//  Created by Stan on 2017-02-13.
//  Copyright © 2017 stan. All rights reserved.
//

import UIKit

class STHeartViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        let heartImage = UIImage(named: "heart")
        
//        设置❤️图层的位置
        let heartLayer = createLayer(position:CGPoint(x: self.view.center.x, y: 100)
            , backgroundColor: UIColor.white)
        
//        将❤️图层绘制上图片
        heartLayer.contents = heartImage?.cgImage
        
//        为❤️图层添加动画
        heartLayer.add(createAnimation(), forKey: nil)
        
        
        
//        添加照片层
        let photoImageView = UIImageView.init(image: UIImage.init(named: "photo"))
        self.view.addSubview(photoImageView)
        
//        设置照片的位置
        photoImageView.center = self.view.center
        photoImageView.bounds = CGRect(x: 0, y: 0, width: 300, height: 320)
        
        
//        设置照片消失的动画
        UIView.animate(withDuration: 2.0) {
            photoImageView.alpha = 0
        }
        
        
    }
}


//MARK: - 抽取创建动画及Layer的公共方法
extension STHeartViewController {
    
    //    创建calayer
    fileprivate func createLayer (position: CGPoint, backgroundColor: UIColor) -> CALayer {
        //创建calayer
        let layer = CALayer()
        //设置位置和大小
        layer.position = position
        layer.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
        
        //设置背景颜色
        layer.backgroundColor = backgroundColor.cgColor
        //把layer添加到UIView的layer上
        self.view.layer.addSublayer(layer)
        
        return layer
    }
    
    
    
    //创建基础Animation
    fileprivate func createAnimation () -> CABasicAnimation {
        //创建动画对象
        let scaleAni = CABasicAnimation()
        //设置动画属性
        scaleAni.keyPath = "transform.scale"
        
        //设置动画的起始位置。也就是动画从哪里到哪里。不指定起点，默认就从positoin开始
        scaleAni.toValue = 0.5
        
        //动画持续时间
        scaleAni.duration = 1.0;
        
//        动画的节奏
        scaleAni.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
        
//        动画持续重复次数
        scaleAni.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
        
        return scaleAni;
    }
    
    
}
